#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 9999
#define BUFFER_SIZE 1024

int main() {
    int sockfd;
    struct sockaddr_in servaddr;
    char buf[BUFFER_SIZE];

    // 创建套接字
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(SERVER_PORT);
    inet_pton(AF_INET, SERVER_IP, &servaddr.sin_addr);

    // 连接服务器
    if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
        perror("connect error");
        exit(1);
    }
    printf("Connected to server\n");

    // 输入循环
    while (1) {
        printf("Enter message: ");
        fgets(buf, BUFFER_SIZE, stdin);
        if (strcmp(buf, "exit\n") == 0) break;

        // 发送数据
        write(sockfd, buf, strlen(buf));

        // 接收回显
        int n = read(sockfd, buf, BUFFER_SIZE);
        if (n <= 0) {
            perror("server closed");
            break;
        }
        buf[n] = '\0';
        printf("Echo: %s", buf);
    }

    close(sockfd);
    return 0;
}